import api from '../../../api/index';
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    images: [],
    goodslist: null,
    dizhidata:[
      {name:'夏雨荷1',telephone:'18630788661',dizhi:'河北省1廊坊市广阳区新源道与百合道交叉口西撒娇分开了的撒娇分离看'},
      {name:'夏雨荷2',telephone:'18630788662',dizhi:'河北省2廊坊市广阳区新源道与百合道交叉口西撒娇分开了的撒娇分离看'},
      {name:'夏雨荷3',telephone:'18630788663',dizhi:'河北省3廊坊市广阳区新源道与百合道交叉口西撒娇分开了的撒娇分离看'},
      {name:'夏雨荷4',telephone:'18630788664',dizhi:'河北省4廊坊市广阳区新源道与百合道交叉口西撒娇分开了的撒娇分离看'},
      {name:'夏雨荷5',telephone:'18630788665',dizhi:'河北省5廊坊市广阳区新源道与百合道交叉口西撒娇分开了的撒娇分离看'}
    ],
    show: false,
    radio: '1',
    deliveraddressList:[],
    showshop: false,
    value: 2,
    username3: '2323sfd',
    shopCartItems: []
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const {ids} = options
    const toast = Toast.loading({
			// duration: 0, // 持续展示 toast
			forbidClick: true,
			message: '正在加载...',
			zIndex: 100000,
			position: 'top',
			selector: '#custom-selector'
		});
		this.setData({
			toast: toast
    });
    // const {id} = options
    // this.loadDesic(id);
    this.loadBasketData(ids)
    this.deliveraddressList()
  },
  showPopup() {
    this.setData({ show: true });
  },

  onClose() {
    this.setData({ show: false });
  },
  goChangeAdress() {
    wx.navigateTo({ url: '/shop/pages/deliveraddress/index' });
  },
  onChange(event) {
    console.log(event);
    this.setData({
      radio: event.detail,
    });
  },
  onChangeNum() {
    Toast.loading({ forbidClick: true });

    setTimeout(() => {
      Toast.clear();
      this.setData({ value });
    }, 500);
  },
  minus(e) {
    console.log(e);
    var id = e.currentTarget.dataset.id
    this.onGoodsClick(id,-1)
  },
  plus(e) {
    console.log(e);
    var id = e.currentTarget.dataset.id
    this.onGoodsClick(id,1)
  },
  // onChangeamount(e) {
  //   console.log(e);
  //   var id = e.currentTarget.dataset.id
  //   var num = e.detail
  //   this.onGoodsClick(id,num)
  // },
    // 商品添加数量
    async onGoodsClick(id,num) {
      const actions = {
        data: {
          goodsamount: num,
          goodsid: id
        }
      }
      try {
        const res = await api.post('/api/hxhealth/shopcart/save',actions);
        console.log(res);
        wx.showToast({
          title: '操作成功！',
          icon: 'none',
          duration: 3000
        });
        this.loadBasketData()
      } catch (e) {
        console.log('deliveraddressList->', e);
        return null;
      }
    },
    // 订单
// /api/hxhealth/shoporder/list
   // 加载订单信息数据
   loadBasketData(ids) {
     console.log(ids);
    //  let arr = ids.split(',')
    wx.showLoading(); //加载订单信息数据
    try {
        api.post('/api/hxhealth/shoporder/load/15645229').then((res) => {
            console.log(res);
            console.log('----res shopCartItems-加载订单信息数据---', res);
            if (res.length > 0) {
              var array = res
              for (let p = 0; p < array.length; p++) {
                  // 默认不选中
                const shopCartItems = array[p].items || [];
                shopCartItems.forEach(shopCartItem => {
                    shopCartItem.prodName = shopCartItem?.goodsid?.[1] || '';
                    // shopCartItem.id = shopCartItem?.goodsid?.[0] || '';
                    shopCartItem.goodsimages = this.getImgUrl(shopCartItem)
                });
                res[p].items = shopCartItems
              }
              console.log(res);
              this.setData({
                list: res
            });
                
            } else {
                this.setData({
                    list: []
                });
            }
            // this.calTotalPrice(); //计算总价
            wx.hideLoading();
        });
    } catch (e) {
        console.error(e);
    }
},
getImgUrl(element) {
  console.log(element);
  var images = element.goodsimages;
  // 判断是否为数组转换的字符串
  let resultUrl = ''
  if (images.startsWith('[')) {
      // 是数组转换的字符串，进行处理
      // console.log('第一种情况：数组转换的字符串', i, images);
      var imagesArray = JSON.parse(images);
      resultUrl = imagesArray?.[0]?.file || '';
      // console.log("第一种情况：数组转换的字符串");
  } else {
      // console.log('第二种情况：逗号隔开的图片地址');
      // 是逗号隔开的图片地址，进行处理
      var imageUrls = images.split(',');
      resultUrl = imageUrls?.[0] || '';
  }
  return resultUrl
},


  // 商品信息
  async loadDesic(id) {
    try {
      const res = await api.get(`/api/hxhealth/goods/load/${id}`);
      var images = res[0].images
      if (images.startsWith('[')) {
        var firstImageUrl = []
        var imagesArray = JSON.parse(images);
        for (let i = 0; i < imagesArray.length; i++) {
          firstImageUrl.push(imagesArray[i].file)
        }
        res[0].firstImageUrl = firstImageUrl;
      } else {
        var imageUrls = images.split(',');
        res[0].firstImageUrl = imageUrls;
      }
      console.log(res);
			this.setData({
        goodslist: res[0],
        images: res[0].firstImageUrl
      });
		} catch (e) {
			console.log('goodslist->', e);
			return null;
		}
  },
  onEvaluateClick() {

  },
  // 获取收货地址列表
  async deliveraddressList() {
    const actions = {
			data: {
        name: '',
			}
		}
    try {
      const res = await api.post('/api/hxhealth/deliveraddress/list',actions);
      console.log(res);
		} catch (e) {
			console.log('deliveraddressList->', e);
			return null;
		}
  },
  async onClickButton() {
    console.log('tijiaodingda');
    this.wxpay(this.data.list[0].code)
  },
  wxpay(orderid) {   
    // let openid = wx.getStorageSync('openid')
    // 必须提供appId,userOrg,orderId,openId
    const actions = {
      data: {
        appId:'wxeed56b13879c5337',
        userOrg:'hongxing',
        // openid,
        orderid
      }
    }
    api.post('/api/hxhealth/shoporder/wxpay',actions).then((res) => {
      console.log(res);
      this.wxrequestPayment(res[0])
      // wx.showToast({
      //       title: '支付',
      //       icon: 'none',
      //       duration: 3000
      //     });
  });
  },
  wxrequestPayment(result) {
    this.setData({
      result
    });
    wx.requestPayment({
      timeStamp: result.timeStamp,
      nonceStr: result.nonceStr,
      package: 'prepay_id='+result.prepayId,
      signType: 'MD5',
      paySign: result.paySign,
      success (res) { 
        console.log(res);
        console.log('支付完成');
        wx.redirectTo({
          url: '/shop/pages/myordersuccess/index'
        })
      },
      fail (res) {
        console.log(res);
        console.log('支付失败');
        Dialog.confirm({
          cancelButtonTrext: '放弃',
          confirmButtonText: '继续付款',
          cancelButtonColor: 'dimgrey',
          confirmButtonColor: 'dodgerblue',
          message: '确认要放弃付款码',
        })
          .then(() => {
            this.wxpay(this.data.list[0].code)
          })
          .catch(() => {
            console.log('2222');
          });
       }
    })
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})